package com.example.myapplication.Activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.Adapter.HDWanAdapter;
import com.example.myapplication.R;
import com.example.myapplication.utils.HDWan_Item_Util;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private Button hdWan_btn1, hdWan_btn2;
    private WebView hdWan_wv1;
    private ListView hdWan_lv1;
    private PullToRefreshListView plv1;
    private TextView hdWan_tv1;
    private ImageView hdWan_iv1;

    private String url = "http://www.hdwan.net";
    ArrayList<HDWan_Item_Util> hdWan_item_utils;
    ArrayList<HDWan_Item_Util> hdWan_item_utils_temp = new ArrayList<>();   //缓存处理
    HDWanAdapter hdWanAdapter;


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            Bundle bundle = msg.getData();
//            String filmName = bundle.getString("filmName");
//            String url = bundle.getString("url");
//            String img = bundle.getString("img");
//
//            HDWan_Item_Util hdWan_item_util = new HDWan_Item_Util(url,img,filmName,"");
//
//            hdWan_item_utils.add(hdWan_item_util);
            //hdWan_tv1.append(filmName + "\n");
            //loadImageVolley(img,hdWan_iv1);
            switch (msg.what) {
                case 0: {
                    Bundle bundle = msg.getData();
                    String filmName = bundle.getString("filmName");
                    String url = bundle.getString("url");
                    String img = bundle.getString("img");
                    String category = bundle.getString("category");
                    HDWan_Item_Util hdWan_item_util = new HDWan_Item_Util(url, img, filmName, category);

//                    if(hdWan_item_utils.size()>50){
//                        hdWan_item_utils.remove(0);
//                    }
                    hdWan_item_utils.add(hdWan_item_util);
                    //hdWan_item_utils = hdWan_item_utils_temp;
                    hdWanAdapter.notifyDataSetChanged();
                    //plv1.setAdapter(hdWanAdapter);
                    Log.i("info", "size=" + hdWan_item_utils.size());
                }
                break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        ParseHtml(url);
        hdWan_item_utils = new ArrayList<>();
        hdWanAdapter = new HDWanAdapter(getApplicationContext(), hdWan_item_utils);
        plv1.setAdapter(hdWanAdapter);

    }

    private void initView() {
        hdWan_btn1 = (Button) findViewById(R.id.hdWan_btn1);
        hdWan_btn2 = (Button) findViewById(R.id.hdWan_btn2);
        hdWan_wv1 = (WebView) findViewById(R.id.hdWan_wv1);
        hdWan_lv1 = (ListView) findViewById(R.id.hdWan_lv1);
        plv1 = (PullToRefreshListView) findViewById(R.id.hdWan_plv1);
        hdWan_wv1.setVisibility(View.GONE);
        hdWan_lv1.setVisibility(View.GONE);
        hdWan_btn1.setVisibility(View.GONE);
        hdWan_btn2.setVisibility(View.GONE);

        hdWan_btn1.setOnClickListener(this);
        hdWan_btn2.setOnClickListener(this);
        plv1.setOnItemClickListener(this);
        plv1.setMode(PullToRefreshBase.Mode.BOTH);
        plv1.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                Toast.makeText(getApplicationContext(), "onPullDownToRefresh", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                new GetDataLast().execute();
                Toast.makeText(getApplicationContext(), "onPullUpToRefresh", Toast.LENGTH_SHORT).show();
            }
        });

    }


    //异步任务去获取资源并更新UI
    private class GetDataLast extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            int page = hdWan_item_utils.size() / 21 + 1;
            Log.i("info", "page=" + page);
            ParseHtml(url + "/page/" + page);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            plv1.onRefreshComplete();
            super.onPostExecute(aVoid);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.hdWan_btn1: {
                hdWan_wv1.setVisibility(View.VISIBLE);
                hdWan_wv1.getSettings().setJavaScriptEnabled(true);
                hdWan_wv1.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        view.loadUrl(url);
                        return true;
                    }
                });
                hdWan_wv1.loadUrl("http://www.hdwan.net/");
            }
            break;
            case R.id.hdWan_btn2: {
                hdWan_wv1.setVisibility(View.GONE);
                ParseHtml(url);

            }
            break;
        }
    }

    private void ParseHtml(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Document doc = Jsoup.connect(url).
                            userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)").timeout(5000).get();
                    Elements elements = doc.select("#post_container").first().children();
                    //Elements elements = doc.select("li.post").select("li.box").select("li.row").select("li.masonry-brick");
                    for (Element ele : elements) {
                        //获取FilmName
                        String filmName = ele.getElementsByTag("h2").first().text();
                        //Elements elements1 = ele.getElementsByTag("thumbnail");

                        //获取img图片的Src
                        Elements elements1 = ele.select("div.thumbnail");
                        Element element1 = elements1.first();
                        Elements elements2 = element1.getElementsByTag("a");
                        Element element2 = elements2.first();
                        String string = element2.attr("href");
                        Elements elements3 = element2.getElementsByTag("img");
                        String imgSrc = elements3.attr("src");

                        //获取分类
                        Elements elements4 = ele.select("div.info");
                        Element element = elements4.first();
                        Elements elements5 = element.select("span.info_category");
                        Element element3 = elements5.first();
                        String category = element3.text();

                        //HDWan_Item_Util hdWan_item_util = new HDWan_Item_Util(string, string2, filmName, "");
                        //hdWan_item_utils_temp.add(hdWan_item_util);
                        //hdWan_item_utils.add(hdWan_item_util);


                        Message msg = new Message();
                        msg.what = 0;
                        Bundle bundle = new Bundle();
                        bundle.putString("img", imgSrc);
                        bundle.putString("filmName", filmName);
                        bundle.putString("url", string);
                        bundle.putString("category",category);
                        msg.setData(bundle);
                        mHandler.sendMessage(msg);

                        //Log.i("info", picUrl);
                    }
                    //Log.i("info", doc.html());
                } catch (IOException e) {
                    Log.i("info", "error");
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        HDWan_Item_Util hdWan_item_util = hdWan_item_utils.get(position);
        String url = hdWan_item_util.getUrl();
        //Toast.makeText(getApplicationContext(), hdWan_item_util.getUrl(), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        intent.putExtra("url", url);
        intent.setClass(getApplicationContext(), ContentActivity.class);
        startActivity(intent);
    }


}
